// pages/user/record-detail/message/message.js
import {getStorageSync} from "../../../../utils/Storage";
import {verifyInput, getDate} from "../../../../utils/Util";
import Static from "../../../../utils/Static";
import {updateRecord} from "../../../../service/Record";
import {sendMessage} from "../../../../service/Open";
import Message from "../../../../service/Message";
import Toast from "@vant/weapp/toast/toast";
import Dialog from "@vant/weapp/dialog/dialog";
Component({

    options: {
        addGlobalClass: true,
        multipleSlots: true
    },

    /**
     * 组件的属性列表
     */
    properties: {
        show: {
            type: Boolean,
            value: false
        },
        detail: {
            type: Object,
            value: {}
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        _fileSavePath: "", //上传图片路径
        _message: {
            show: false,
            focus: false,
            loading: false,
            error: ""
        },
        _formData: {
            message: "",
            images: [],
            rid: ""
        },
        _list: [],
        _total: 0,
        _delLoading: false
    },


    ready: function () {
        let openId = getStorageSync("userInfo.openId");
        this.setData({
            _fileSavePath: "message/" + (openId ? openId + "/" : "")
        })
    },

    /*
    * 数据监听
    * */
    observers: {
        show: function (val) {
            if (val) {
                const that = this;
                that.setData({"_message.show": true}, function () {
                    setTimeout(function () {
                        that.setData({"_message.focus": true})
                    }, 500)
                })
            }
        },
        detail: function (val) {
            if (val) {
                // this.setData({"_formData.rid": val});
                this.data._formData.rid = val._id;
                this.data._formData.rOpenId = val.openId;
                this.getMessageList();
            }
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        //关闭对话框
        onMessageClose: function () {
            this.setData({
                "_message.show": false,
                "_message.focus": false
            })
        },
        //文本输入
        onInputChange: function (e) {
            let error = this.data._message.error;
            this.setData({
                "_formData.message": e.detail
            })
            error ? this.setData({
                "_message.error": ""
            }) : null
        },
        //图片上传
        onUploadFile: function (e) {
            this.data._formData.images = e.detail.result.map(function (item) {
                return item.id
            })
        },
        //发布消息
        onMessageAdd: async function () {
            try {
                const that = this;
                let detail = that.data.detail;
                let formData = that.data._formData;
                let templateId = Static.templateId.lytz;
                let userInfo = getStorageSync("userInfo") || {};
                let total = that.data._total;
                let list = that.data._list;
                if (!verifyInput(formData.message)) {throw {inputErrorMsg: "留言信息不能为空"}};
                that.setData({
                    "_message.focus": false,
                    "_message.loading": true
                })
                let res = await Message.addMessage(formData);
                list.unshift({
                    _id: res._id,
                    avatarUrl: userInfo.avatarUrl,
                    nickName: userInfo.nickName,
                    openId: userInfo.openId,
                    message: formData.message,
                    images: formData.images,
                    createTime: getDate(new Date().getTime()).split(" ")[0]
                })
                that.setData({
                    _list: list,
                    _total: total + 1,
                    "_message.loading": false,
                    "_message.show": false,
                    _formData: { //重置数据
                        message: "",
                        images: [],
                        rid: ""
                    }
                });
                that._sendMessage();
                if (userInfo.openId !== detail.openId && detail[templateId] > 0) {  //不是本人留言且模板订阅次数大于0 则发送消息通知
                    await sendMessage({
                        openId: detail.openId,
                        page: "pages/user/record-detail/record-detail?id=" + detail._id,
                        data: {
                            name1: {
                                value: userInfo.nickName
                            },
                            thing2: {
                                value: formData.message
                            },
                            time3: {
                                value: getDate(new Date().getTime()).split(" ")[0]
                            }
                        },
                        templateId: templateId,
                        miniprogramState: Static.config.miniprogramState
                    })
                    await updateRecord(detail._id, {
                        [templateId]: detail[templateId] - 1
                    })
                    that.setData({
                        ["detail." + templateId]: detail[templateId] - 1
                    })
                }
            } catch (e) {
                if (e.name) {
                    console.error(e)
                } else {
                    this.setData({"_message.error": e.inputErrorMsg});
                }
            }
        },

        /*
        * 删除操作
        * */
        onMessageDelete: async function (e) {
            try {
                if (this.data._delLoading) {throw ""}; //删除操作中禁止其它操作
                let list = this.data._list;
                let index = e.currentTarget.dataset.index;
                let id = list[index]._id;
                await Dialog.confirm({
                    title: "提示",
                    message: "是否删除该条内容",
                    context: this,
                    selector: "#van-dialog_message"
                })
                this.setData({_delLoading: true})
                await Message.deleteMessage(id);
                list.splice(index, 1);
                this.setData({
                    _delLoading: false,
                    _list: list,
                    _total: this.data._total - 1
                })
                this._sendMessage();
            } catch (e) {
                if (e.name) {
                    Toast.fail({
                        message: "删除失败",
                        context: this,
                        selector: "#van-toast_message"
                    })
                    console.error(e)
                }
                this.setData({_delLoading: false})
            }
        },

        /*
        * 获取留言列表
        * */
        getMessageList: async function () {
            try {
                let rOpenId = this.data.detail.openId;
                let rid = this.data.detail._id;
                let userInfo = getStorageSync("userInfo") || {}
                let res = await Message.getMessageList({
                    page: 1,
                    pageSize: 100,
                    rid: rid,
                    verify: [0, 1]
                })
                let filterArr = !userInfo.isManager && rOpenId !== userInfo.openId ? res.list.filter(function (item) { //只有发布消息的人 和 发布留言的人以及管理员才能看到 留言
                    return item.openId === userInfo.openId
                }) : res.list;
                this.setData({
                    _list: filterArr.map(function (item) {
                        return {
                            _id: item._id,
                            avatarUrl: item.avatarUrl,
                            nickName: item.nickName,
                            message: item.message,
                            openId: item.openId,
                            images: item.images,
                            createTime: getDate(item.createTime).split(" ")[0]
                        }
                    }),
                    _total: res.list.length
                })
            } catch (e) {
                console.error(e)
            }
        },

        /*
        * 通知父组件
        * */
        _sendMessage: function () {
            this.triggerEvent("message", {
                status: "success",
                result: {}
            }, {}); //组件接收函数写入数据
        },

        /*
        * 预览留言图片
        * */
        bindMessagePreviewImage: function (e) {
            let current = e.currentTarget.dataset.src;
            wx.previewImage({
                current: current, // 当前显示图片的http链接
                urls: [current] // 需要预览的图片http链接列表
            })
        }
    }
})
